/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.demo.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.util.Utils;
import com.mol.market.ui.PersonalAccountActivity;
import com.mol.market.ui.SearchActivity;
import com.mol.market.ui_v4.AppManagerActivity;

/**
 * 所有Activity的父类
 *
 * @author Chaos
 * @Description 必须用一个父类控制所有Activity，方便进行统一操作和维护。
 * @date 2013-1-22
 */
@SuppressLint("NewApi")
public class BaseFragmentActivity extends SherlockFragmentActivity {

    public Session mSession;
    
    private int nowNeedUpdateNum = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //当系统本身并不提供actionbar的时候，我们必须取消原本的Title，再使用actionbarsherlock。
        if(android.os.Build.VERSION.SDK_INT <= 11){
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        
        //must set theme for app ,this will make all resources initialization
        DisplayMetrics display = getResources().getDisplayMetrics();
        int style = display.widthPixels / display.density >= 480?R.style.gfan_theme_land:R.style.gfan_theme_port;
        setTheme(style);
        
        updateActionBar(this);
        mSession = Session.get(this);
        
        nowNeedUpdateNum = mSession.getUpgradeNumber();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
//        TCAgent.onResume(this);
        if (nowNeedUpdateNum != mSession.getUpgradeNumber()) {
            nowNeedUpdateNum = mSession.getUpgradeNumber();
            invalidateOptionsMenu();
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();
//        TCAgent.onPause(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.home_menu, menu);

        handleUpdateNum(menu.getItem(1), mSession.getUpgradeNumber(),
                getResources().getDisplayMetrics());
        
        return super.onCreateOptionsMenu(menu);
    }
    
    /**
     * 绘制可更新数字
     */
    private void handleUpdateNum(MenuItem item, int update, DisplayMetrics dm){
        if(update <= 0 || item.getItemId() != R.id.menu_manager){
            return ;
        }

        //注：变量中以 "_" 开头的表示必须手动回收。
        float density = dm.density;
        //获得原始图片
        Bitmap _tempOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.menu_manage);
        //获得更新文字所在的底色        
        Bitmap _tempBackground = BitmapFactory.decodeResource(getResources(), 
                R.drawable.new_update);
        //最终绘制原始图的宽度和高度
        int oriWidth  = (int) (_tempOriginal.getWidth() * density);
        int oriHeight = (int) (_tempOriginal.getHeight() * density); 
        //最终绘制更新底色的宽度和高度
        int dstWidth  = (int) (_tempOriginal.getWidth() * 0.8f * density);
        int dstHeight = (int) (_tempOriginal.getHeight() * 0.4f * density); 
        //缩放绘制底色达到合适的宽度和高度
        Bitmap _updateBg = Bitmap.createScaledBitmap(_tempBackground, dstWidth, 
                dstHeight, true);
        //创建空白的Bitmap为了绘制颜色和
        Bitmap _updateBgWithTextBlack = Bitmap.createBitmap(_updateBg.getWidth(),
                _updateBg.getHeight(),Bitmap.Config.ARGB_8888);
        //准备绘制更新数字
        Canvas updateBgCanvas = new Canvas(_updateBgWithTextBlack);
        updateBgCanvas.drawBitmap(_updateBg, 0, 0, null);
        // -------> 开始在updateBg上绘制文字
        Paint textPainter = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPainter.setColor(Color.WHITE);
        textPainter.setTextSize(dm.scaledDensity * 16);
        textPainter.setTypeface(Typeface.DEFAULT_BOLD);
        float textWidth = textPainter.measureText(String.valueOf(update) + "+") / 2;
        updateBgCanvas.drawText(String.valueOf(update) + "+", 
                _updateBg.getWidth() / 2 - textWidth, 
                _updateBg.getHeight() / 2 + (dm.scaledDensity * 6), textPainter);
        // <------ 绘制更新数字完成
        
        // -------> 将背景 和 已经绘制完成的带更新数量的bitmap绘制在一起
        Bitmap _original = Bitmap.createScaledBitmap(_tempOriginal, oriWidth, 
                oriHeight, true);
        Bitmap blank = Bitmap.createBitmap(oriWidth,
                oriHeight,Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(blank);
        canvas.drawBitmap(_original, 0, 0, null);
        canvas.drawBitmap(_updateBgWithTextBlack, (oriWidth - dstWidth) / 2, 10, null);
        // <------- 所有的都绘制完成
        
        //装载入MenuItem中
        item.setIcon(new BitmapDrawable(blank));
        
        //释放Bitmap中cpp所占用的内存
        try{
        _updateBg.recycle();
        _original.recycle();
        _tempOriginal.recycle();
        _tempBackground.recycle();
        _updateBgWithTextBlack.recycle();
        }catch(RuntimeException e){
            //may be throw 
            //new RuntimeException("Canvas: trying to use a recycled bitmap " + bitmap);
            Utils.E("can not recycle bitmap : ", e);
        }finally{
            _updateBg = null;
            _original = null;
            _tempOriginal = null;
            _tempBackground = null;
            _updateBgWithTextBlack = null;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                onBackPressed();
                return true;
            }
            case R.id.menu_search: {
                Utils.jumpToPage(this, SearchActivity.class, false);
                return true;
            }
//            case R.id.menu_rebate: {
//                Intent i = new Intent(getApplicationContext(), MakeMoneyActivity.class);
//                startActivity(i);
//                Utils.trackEvent(getApplicationContext(), "menu", "赚钱");
//                return true;
//            }
            case R.id.menu_manager: {

                Intent i = new Intent(getApplicationContext(), AppManagerActivity.class);
                startActivity(i);
                return true;
            }
            case R.id.menu_account: {

                Intent i = new Intent(getApplicationContext(), PersonalAccountActivity.class);
                startActivity(i);
                Utils.trackEvent(getApplicationContext(), "menu", "个人中心");
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    public static void updateActionBar(final Activity activity) {
        if (Build.VERSION.SDK_INT >= 17) {
            try {
                final View content = activity.findViewById(android.R.id.content);
                if (content instanceof FrameLayout) {
                    final FrameLayout contentFrameLayout = (FrameLayout) content;
                    final ViewParent parent = contentFrameLayout.getParent();
                    if (parent instanceof LinearLayout) {
                        final LinearLayout parentLinearLayout = (LinearLayout) parent;
                        final Class<?> actionBarContainerClass = Class.forName("com.android.internal.widget.ActionBarContainer");
                        final Class<?> actionBarViewClass = Class.forName("com.android.internal.widget.ActionBarView");
                        final Class<?> actionMenuViewClass = Class.forName("com.android.internal.view.menu.ActionMenuView");
                        final Class<?> actionMenuItemViewClass = Class.forName("com.android.internal.view.menu.ActionMenuItemView");

                        for (int i = 0, childCount = parentLinearLayout.getChildCount(); i < childCount; i++) {
                            final View parentLinearLayoutChild = parentLinearLayout.getChildAt(i);
                            handleParentLinearLayoutChild(actionBarContainerClass, actionBarViewClass, actionMenuViewClass, actionMenuItemViewClass, parentLinearLayoutChild);
                        }
                    }
                }
            } catch (Exception e) {
                // Handle or ignore
            }
        }
    }

    private static void handleParentLinearLayoutChild(final Class<?> actionBarContainerClass, final Class<?> actionBarViewClass, final Class<?> actionMenuViewClass, final Class<?> actionMenuItemViewClass, final View parentLinearLayoutChild) {
        if (parentLinearLayoutChild instanceof FrameLayout && parentLinearLayoutChild.getClass().equals(actionBarContainerClass)) {
            final FrameLayout actionBarContainer = (FrameLayout) parentLinearLayoutChild;
            for (int i = 0, actionBarContainerChildCount = actionBarContainer.getChildCount(); i < actionBarContainerChildCount; i++) {
                final View actionBarContainerChild = actionBarContainer.getChildAt(i);
                handleActionBarContainerChild(actionBarViewClass, actionMenuViewClass, actionMenuItemViewClass, actionBarContainerChild);
            }
        }
    }

    private static void handleActionBarContainerChild(final Class<?> actionBarViewClass, final Class<?> actionMenuViewClass, final Class<?> actionMenuItemViewClass, final View actionBarContainerChild) {
        if (actionBarContainerChild instanceof ViewGroup && actionBarContainerChild.getClass().equals(actionBarViewClass)) {
            final ViewGroup actionBarView = (ViewGroup) actionBarContainerChild;
            actionBarView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
                @Override
                public void onChildViewAdded(final View parent, final View child) {
                    handleActionBarViewChild(child, actionMenuViewClass, actionMenuItemViewClass);
                }

                @Override
                public void onChildViewRemoved(final View parent, final View child) {
                }
            });
            for (int i = 0, actionBarViewCount = actionBarView.getChildCount(); i < actionBarViewCount; i++) {
                handleActionBarViewChild(actionBarView.getChildAt(i), actionMenuViewClass, actionMenuItemViewClass);
            }
        }
    }

    private static void handleActionBarViewChild(final View child, final Class<?> actionMenuViewClass, final Class<?> actionMenuItemViewClass) {
        try {
            if (child instanceof LinearLayout && child.getClass().equals(actionMenuViewClass)) {
                final LinearLayout actionMenuView = (LinearLayout) child;
                actionMenuView.setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
                    @Override
                    public void onChildViewAdded(final View parent, final View child) {
                        handleActionMenuViewChild(child, actionMenuItemViewClass);
                    }

                    @Override
                    public void onChildViewRemoved(final View parent, final View child) {
                    }
                });
                for (int i = 0, actionMenuViewCount = actionMenuView.getChildCount(); i < actionMenuViewCount; i++) {
                    handleActionMenuViewChild(actionMenuView.getChildAt(i), actionMenuItemViewClass);
                }
            }
        } catch (Exception e) {
            // Handle or ignore
        }
    }

    private static void handleActionMenuViewChild(final View child, final Class<?> actionMenuItemViewClass) {
        try {
            if (child instanceof TextView && child.getClass().equals(actionMenuItemViewClass)) {
                final TextView menuViewChild = (TextView) child;
                final Drawable[] compoundDrawables = menuViewChild.getCompoundDrawables();
                final Drawable leftDrawable = compoundDrawables[0];
                final int intrinsicWidth = leftDrawable.getIntrinsicWidth();
                final int intrinsicHeight = leftDrawable.getIntrinsicHeight();
                leftDrawable.setBounds(0, 0, intrinsicWidth , intrinsicHeight );
                menuViewChild.setCompoundDrawables(leftDrawable, null, null, null);
                menuViewChild.setPadding(menuViewChild.getPaddingLeft(), 0, menuViewChild.getPaddingRight(), 0);
                menuViewChild.invalidate();
                menuViewChild.requestLayout();
            }
        } catch (Exception e) {
            // Handle or ignore
        }
    }
    
    /**
     * 在不同Activity，Fragment中跳转，用来存储跳转的Key，arg以及target。
     *
     * @author Chaos
     * @date 2013-1-22
     */
    public static interface KeyStore {
        /**
         * 用作进入Activity的入口
         */
        String KEY_ENTRY = "entry.key";
        /**
         * 应用 -- 应用分类
         */
        String TARGET_CATEGORY_APP = "app.category.target";
        /**
         * 游戏 -- 游戏分类
         */
        String TARGET_CATEGORY_GAME = "game.category.target";
        /**
         * 应用 -- 精选标签
         */
        String TARGET_CATEGORY_TAG_APP = "app.tag.category.target";
        /**
         * 游戏 -- 精选标签
         */
        String TARGET_CATEGORY_TAG_GAME = "game.tag.category.target";
        /**
         * 精选标签 -- 标签列表(List)
         */
        String TARGET_CATEGORY_TAG_LIST = "list.tag.category.target";
        /**
         * （游戏/应用）分类  -- 分类列表(Tab)
         */
        String TARGET_CATEGORY_TAB_LIST = "list.tab.category.target";
        /**
         * 猜你喜欢
         */
        String TARGET_GENIUS = "list.genius";
        /**
         * 专题
         */
        String TARGET_TOPICS = "list.topics";


        /**
         * 一般用作Map的Key，用于传输给Fragment当作参数。
         */
        String KEY_ARG = "arg.key";

        String KEY_TITLE = "title.key";
    }
}
